/**
* All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
*
* AppAreaInitializationConfigService
* 区域初始化配置
*
* 修改纪录
* 2022-12-23 版本：1.0 wuyuyang 创建。
* @version 版本：1.0
* @author 作者：wuyuyang
* 创建日期：2022-12-23
*/
package com.topscomm.appv2.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.topscomm.appv2.SystemConst;
import com.topscomm.appv2.pojo.AppAreaInitializationConfigEntity;
import com.topscomm.appv2.pojo.AppUserUseInfoEntity;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.pojo.CboModuleEntity;
import com.topscomm.cbo.service.ICboModuleService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.appv2.service.IAppAreaInitializationConfigService;
import com.topscomm.appv2.service.impl.auto.AppAreaInitializationConfigServiceAuto;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(value = "appAreaInitializationConfigService")
@Scope(value = "singleton")
public class AppAreaInitializationConfigService extends AppAreaInitializationConfigServiceAuto implements IAppAreaInitializationConfigService {
    @Autowired
    private AppUserUseInfoService appUserUseInfoService;
    @Autowired
    private ICboModuleService cboModuleService;

    /**
     * @Description:    用户信息表金刚区强制更新
     * @Author:         wuyuyang
     * @Return:         void
     * @exception:
     * @Date:           2/1/2023 下午9:03
     * @Version:        1.0
     **/
    @Transactional
    public boolean updateForceAppUserInfoCorearea(List<AppAreaInitializationConfigEntity> appAreaInitializationConfigEntityList, Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        // 取有效用户
        sql.appendSingle("enabled = {0}", SystemConst.Enabled_Yes);
        List<AppUserUseInfoEntity> appUserUseInfoList = appUserUseInfoService.queryByWhere(sql.toString());
        List<BasicEntity> appUserUseInfoListNew = new ArrayList<BasicEntity>();
        if (appUserUseInfoList.size() > 0) {
            // 遍历用户，强制更新每个用户的金刚区默认值
            String coreareaDefaultvalue = appAreaInitializationConfigEntityList.get(0).getDefaultvalue();
            for (AppUserUseInfoEntity appUserUseInfoEntity : appUserUseInfoList) {
                appUserUseInfoEntity.setCorearea(coreareaDefaultvalue);
                appUserUseInfoListNew.add(appUserUseInfoEntity);
            }
            // 批量更新用户信息
            appUserUseInfoService.updateBatch(appUserUseInfoListNew);
            return true;
        }
        return false;
    }

    /**
     * @Description:    用户信息表金刚区最大数量强制更新
     * @Author:         wuyuyang
     * @Return:         java.lang.String
     * @exception:
     * @Date:           3/1/2023 上午10:16
     * @Version:        1.0
     **/
    @Transactional
    public boolean updateForceAppUserInfoCoreareaMaxnum(List<AppAreaInitializationConfigEntity> appAreaInitializationConfigEntityList) {
        StringBufferProxy sql = new StringBufferProxy();
        // 取有效用户
        sql.appendSingle("enabled = {0}", SystemConst.Enabled_Yes);
        List<AppUserUseInfoEntity> appUserUseInfoList = appUserUseInfoService.queryByWhere(sql.toString());
        List<BasicEntity> appUserUseInfoListNew = new ArrayList<BasicEntity>();
        if (appUserUseInfoList.size() > 0) {
            // 获取用户配置的金刚区最大数与默认值
            String maxnum = appAreaInitializationConfigEntityList.get(0).getMaxnum();
            // 最大数转换成整型
            int maxnum1 = ConvertUtil.convertToInt(maxnum);
            String coreareaDefaultValue = appAreaInitializationConfigEntityList.get(0).getDefaultvalue();
            for (AppUserUseInfoEntity appUserUseInfoEntity : appUserUseInfoList) {
                String corearea = appUserUseInfoEntity.getCorearea();
                // 字符串转为JSONArray，用户现有金刚区数量小于默认值则截取
                JSONArray coreareaJsonArray = JSONArray.parseArray(corearea);
                JSONArray coreareaJsonArrayNew = new JSONArray();
                if (StringUtils.isEmpty(corearea)) {
                    appUserUseInfoEntity.setCorearea(coreareaDefaultValue);
                    // 最终将处理后的金刚区放入用户信息
                    appUserUseInfoListNew.add(appUserUseInfoEntity);
                    // 金刚区最大值不为空且金刚区最大数小于用户金刚区现有值的数量
                } else if (!StringUtils.isEmpty(maxnum) && maxnum1 < coreareaJsonArray.size()) {
                    // 循环处理新JSONArray的值
                    for (int i = 0; i < maxnum1; i++) {
                        coreareaJsonArrayNew.add(coreareaJsonArray.get(i));
                    }
                    appUserUseInfoEntity.setCorearea(coreareaJsonArrayNew.toString());
                    // 最终将处理后的金刚区放入用户信息
                    appUserUseInfoListNew.add(appUserUseInfoEntity);
                } else {
                    //不做任何处理
                }
            }
            // 如果用户信息有修改、则批量更新用户信息，否则不做任何处理
            if (appUserUseInfoListNew.size() > 0) {
                appUserUseInfoService.updateBatch(appUserUseInfoListNew);
            }
            return true;
        }
        return false;
    }

    /**
     * @Description:    用户信息表最近使用最大数强制更新
     * @Author:         wuyuyang
     * @Return:         java.lang.String
     * @exception:
     * @Date:           3/1/2023 下午2:12
     * @Version:        1.0
     **/
    public boolean updateForceAppUserInfoRecentlyusedareaMaxnum(List<AppAreaInitializationConfigEntity> appAreaInitializationConfigEntityList) {
        StringBufferProxy sql = new StringBufferProxy();
        // 取有效用户
        sql.appendSingle("enabled = {0}", SystemConst.Enabled_Yes);
        List<AppUserUseInfoEntity> appUserUseInfoList = appUserUseInfoService.queryByWhere(sql.toString());
        List<BasicEntity> appUserUseInfoList2 = new ArrayList<BasicEntity>();
        if (appUserUseInfoList.size() > 0) {
            // 获取用户配置的最近使用的最大数
            String maxnum = appAreaInitializationConfigEntityList.get(0).getMaxnum();
            // 最大数转换成整型      1
            int maxnum1 = ConvertUtil.convertToInt(maxnum);
            for (AppUserUseInfoEntity appUserUseInfoEntity : appUserUseInfoList) {
                String recentlyusedarea = appUserUseInfoEntity.getRecentlyusedarea();
                // 字符串转为JSONArray，用户现有最近使用数量小于最大值则截取
                JSONArray recentlyusedareaJsonArray = JSONArray.parseArray(recentlyusedarea);
                JSONArray recentlyusedareaJsonArrayNew = new JSONArray();
                if (StringUtils.isEmpty(recentlyusedarea)) {
                    // 数据为空不做任何处理
                } else if (!StringUtils.isEmpty(maxnum) && maxnum1 < recentlyusedareaJsonArray.size()){
                    // 循环处理新JSONArray的值
                    for (int i = 0; i < maxnum1; i++) {
                        recentlyusedareaJsonArrayNew.add(recentlyusedareaJsonArray.get(i));
                    }
                    appUserUseInfoEntity.setRecentlyusedarea(recentlyusedareaJsonArrayNew.toString());
                    // 最终将处理后的最近使用信息放入用户信息
                    appUserUseInfoList2.add(appUserUseInfoEntity);
                }else {
                    // 其他情况不做任何处理
                }
            }
            // 如果用户信息有修改、则批量更新用户信息，否则不做任何处理
            if (appUserUseInfoList2.size() > 0) {
                appUserUseInfoService.updateBatch(appUserUseInfoList2);
            }
            return true;
        }
        return false;

    }

    /**
     * @Description:    用户信息表一级目录强制更新
     * @Author:         wuyuyang
     * @Return:         java.lang.String
     * @exception:
     * @Date:           3/1/2023 下午8:33
     * @Version:        1.0
     **/
    @Transactional
    public boolean updateForceAppUserInfoFirstleveldirectory(List<AppAreaInitializationConfigEntity> appAreaInitializationConfigEntityList) {
        StringBufferProxy sql = new StringBufferProxy();
        // 取有效用户
        sql.appendSingle("enabled = {0}", SystemConst.Enabled_Yes);
        List<AppUserUseInfoEntity> appUserUseInfoList = appUserUseInfoService.queryByWhere(sql.toString());
        List<BasicEntity> appUserUseInfoListNew = new ArrayList<BasicEntity>();
        if (appUserUseInfoList.size() > 0) {
            // 遍历用户，强制更新每个用户的一级目录默认值
            String FirstleveldirectoryDefaultvalue = appAreaInitializationConfigEntityList.get(0).getDefaultvalue();
            for (AppUserUseInfoEntity appUserUseInfoEntity : appUserUseInfoList) {
                appUserUseInfoEntity.setFirstleveldirectory(FirstleveldirectoryDefaultvalue);
                appUserUseInfoListNew.add(appUserUseInfoEntity);
            }
            // 批量更新用户信息
            appUserUseInfoService.updateBatch(appUserUseInfoListNew);
            return true;
        }
        return false;
    }

    /**
     * @Description:    处理用户信息
     * @Author:         hudeyong
     * @exception:
     * @Date:           2023/05/24
     * @Version:        1.0
     **/
    @Transactional
    public void updateUserinfo(Map<String, Object> paraMap){
        // 验证参数
        String code =ConvertUtil.convertToString(paraMap.get("code"));
        String name =ConvertUtil.convertToString(paraMap.get("name"));
        int index =ConvertUtil.convertToInt(paraMap.get("index"));
        String changeType =ConvertUtil.convertToString(paraMap.get("changeType"));
        if(code.isEmpty() || index == 0 || changeType.isEmpty()){
            throw new ServiceException("传参错误");
        }
        // 初始化修改的参数
        String fieldName = "";
        if(SystemConst.AppAreaType.corearea.equals(changeType)){
            fieldName= AppUserUseInfoEntity.FieldCorearea;
        } else if (SystemConst.AppAreaType.firstleveldirectory.equals(changeType)){
            fieldName= AppUserUseInfoEntity.FieldFirstleveldirectory;
        } else if(SystemConst.AppAreaType.extendfield1.equals(changeType)){
            fieldName= AppUserUseInfoEntity.FieldExtendfield1;
        }else {
            return;
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("code = '{0}'",code);
        List<CboModuleEntity> cboModuleEntities = cboModuleService.queryByWhere(sql.toString());
        if(cboModuleEntities.size()==0){
            return;
        }
        sql.clear();
        sql.appendSingle("FIELDNAME = '{0}'",fieldName);
        List<AppAreaInitializationConfigEntity> appConfigList = this.queryByWhere(sql.toString());
        if(appConfigList.size()==0){
            return;
        }
        int maxNum = ConvertUtil.convertToInt(appConfigList.get(0).getMaxnum());
        Map<String, Object> insertMap = new HashMap<>();
        insertMap.put("code",cboModuleEntities.get(0).getCode());
        insertMap.put("name",cboModuleEntities.get(0).getName());
        insertMap.put("sortcode",index);
        // 取所有用户
        sql.clear();
        List<AppUserUseInfoEntity> appUserUseInfoList = appUserUseInfoService.queryByWhere("1=1");
        List<BasicEntity> changeUserList = new ArrayList<>();
        // 遍历每个用户,先去除要修改位置的模块
        for (AppUserUseInfoEntity appUserUseInfoEntity : appUserUseInfoList) {
            String userConfig = ConvertUtil.convertToString(appUserUseInfoEntity.getValue(fieldName));
            List<Map<String,Object>> configList = (List<Map<String,Object>>) JSONArray.parse(userConfig);
            for(Map<String,Object> moduleInfo : configList){
                if(code.equals(ConvertUtil.convertToString(moduleInfo.get("code")))){
                    configList.remove(moduleInfo);
                    break;
                }
            }
            //将模块插入到指定位置
            if(configList.size()>=index){
                configList.add(index-1,insertMap);
            } else {
                configList.add(insertMap);
            }
            if(maxNum!=0 && configList.size()>maxNum){
                configList.remove(configList.size()-1);
            }
            userConfig = JSON.toJSONString(configList);
            appUserUseInfoEntity.setValue(fieldName,userConfig);
            changeUserList.add(appUserUseInfoEntity);
        }
        // 批量更新用户信息
        List<String> filedList = new ArrayList<>();
        filedList.add(fieldName);
        appUserUseInfoService.updateFieldsBatch(changeUserList,filedList);
        String defaultValue = ConvertUtil.convertToString(appConfigList.get(0).getDefaultvalue());
        List<Map<String,Object>> configList = (List<Map<String,Object>>) JSONArray.parse(defaultValue);
        // 遍历每个用户,先去除要修改位置的模块
        for(Map<String,Object> moduleInfo : configList) {
            if(code.equals(ConvertUtil.convertToString(moduleInfo.get("code")))){
                configList.remove(moduleInfo);
                //将模块插入到指定位置
                if(configList.size()>=index){
                    configList.add(index-1,insertMap);
                } else {
                    configList.add(insertMap);
                }
                if(maxNum!=0 && configList.size()>maxNum){
                    configList.remove(configList.size()-1);
                }
                sql.clear();
                sql.appendSingle("update {0} set {1} = '{2}' where {3} = '{4}'",
                        AppAreaInitializationConfigEntity.tableName,AppAreaInitializationConfigEntity.FieldDefaultvalue,
                        JSON.toJSONString(configList),AppAreaInitializationConfigEntity.FieldFieldname,fieldName);
                this.updateExecute(sql.toString());
                break;
            }
        }
    }

}
